<script lang="ts" setup>
import { ref, defineProps, watch, onMounted, onBeforeUnmount, provide } from 'vue'
import { useRouter } from 'vue-router'
import { Api } from '@/apis'
import { useCounterStore } from '@/stores/counter'

import x2js from 'x2js'
import '@/assets/video.css'

import type { DefaultDetailData, Durl, Pages } from '@/TypingMore/VideoTyping'
import type { Episodes, FIntroduction, MainSection, DefalutDanMu, DanMuI } from '@/TypingMore/SeasonTyping'
import type { UserBrowseData } from '@/TypingMore/UserTyping'

import VideoIntroduction from '@/components/videocomponents/VideoIntroduction.vue'
import VideoEpisodes from '@/components/videocomponents/VideoEpisodes.vue'
import RecommendComponent from '@/components/videocomponents/RecommendComponent.vue'
import FRecommend from '@/components/videocomponents/FRecommend.vue'
import VideoShow from '@/components/videocomponents/VideoShow.vue'

const props = defineProps<{
    bvid: string
}>()

const store = useCounterStore()

const { follow } = store

const router = useRouter()

const defaultData = <DefaultDetailData>{}

const defaultIntroduction = <FIntroduction>{}

const videoData = ref(defaultData)

const introductionData = ref(defaultIntroduction)

const episodes = ref<Episodes[]>([])

const danmuData = ref<DefalutDanMu[]>([])

const sectionEpisodes = ref<MainSection[]>([])

const like = ref<UserBrowseData[]>([])

const playerData = ref<Durl[]>([])

const collection = ref<UserBrowseData[]>([])

const isLike = ref(false)

const isCollection = ref(false)

const pic = ref('')

const userBvid = ref('')

const season_id = ref(0)

const epIdValue = ref<string | undefined>()

const time = ref(0)

const danmu = ref(0)

const timelength = ref<string | number>(0)

const reallyTimeLength = ref(0)

const page = ref(0)

const activeNames = ref<string[]>(['1'])

const activeIndex = ref(1)

const colorData = ref('color: #fb7299 ; border: 1px solid #fb7299')

const goToUser = (uid: number) => {
    router.push(`/user/${uid}`)
}
const svgTestFun = (h: any) => {
    console.log(h)
}
const svgEls = provide('svgEl', svgTestFun)
console.log(svgEls)

const goToVideos = (bvid: string) => {
    userBvid.value = bvid
    router.replace(`/video/${bvid}`)
}
// 获取视频页面的所有数据
const getVideoData = async () => {
    let { data } = await Api.getDetailData(props.bvid)

    videoData.value = data
    time.value = data.data.View.stat.view
    danmu.value = data.data.View.stat.view

    let epId = data.data.View.redirect_url?.split('ep')[1].replace(/[^\d]/g, "")
    getVideoAndAnthology(epId, videoData.value.data.View.pic)

    timelength.value = parseInt(data.data.View.pages[page.value].duration / 60 + '') + ':' + parseInt(data.data.View.pages[page.value].duration % 60 + '')
    console.log('\n*** VideoData  ****')
    console.log('epId:', epId, data.data.View.redirect_url)
    console.log('视频详情数据(data):', data)
    console.log('*** VideoData  ****')
}
// 获取选集与视频的url
const getVideoAndAnthology = async (epId: string | undefined, picUrl: string) => {
    pic.value = picUrl
    epIdValue.value = epId
    if (epId) {
        await Api.getSectionIdData(epId).then(async ({ data: seasonId }) => {
            console.log(seasonId)
            if (seasonId.data.length > 0) {
                let { data: season } = await Api.getSectionData(seasonId.data[0].season_id)
                season_id.value = seasonId.data[0].season_id
                episodes.value = season.result.main_section.episodes
                sectionEpisodes.value = season.result.section
                console.log('选集(season):', season)
            } else {
                let { data: id } = await Api.getSectionId(epId)
                let { data: season } = await Api.getSectionData(id.result.season_id)
                season_id.value = id.result.season_id
                episodes.value = season.result.main_section.episodes
                sectionEpisodes.value = season.result.section
                console.log('选集(season)data.length<0:', season)
            }
            console.log('*** seasonId ***')
            console.log('选集id(seasonId):', seasonId)
            console.log('*** seasonId ***')
        })
        let { data: urlData } = await Api.getFPlayUrlData(epId)
        let { data: introduction } = await Api.getSeason(epId)

        playerData.value = urlData.result.durl
        reallyTimeLength.value = urlData.result.durl[0].length / 1000
        introductionData.value = introduction.result

        console.log('选集(season):', '\n番剧的url(url):', urlData)
        console.log('真正的视频总时长:', reallyTimeLength.value)

    } else {

        let { data: res } = await Api.getPlaymp4UrlData(videoData.value.data.View.cid, videoData.value.data.View.aid)

        playerData.value = res.data.durl

        reallyTimeLength.value = res.data.durl[0].length / 1000

        console.log('视频url(res):', res, playerData)
    }
}
// 获取弹幕数据
const getDanMuData = async (cid: number) => {
    let { data } = await Api.getDanMu(cid)
    let s = new x2js()
    // xml转json
    let danmu = s.xml2js(data) as DanMuI

    for (let i = 0; i < danmu.i.d.length; i++) {
        console.log('执行力')
        let d = danmu.i.d[i]
        if (d._p instanceof Array) {
            d._p = d._p
        } else {
            d._p = d._p.split(',')
        }
    }
    danmuData.value = danmu.i.d.map(i => {
        return {
            ...i,
            is: Math.floor((Math.random() * 5)) * 30,
            isAdd: false
        }
    })
    console.log('\n***** xml2jsDanMu  *****\n\n', '弹幕的xml数据,目前转为对象(Danmu):', danmu, danmuData.value, '\n\n***** xml2jsDanMu   *****\n')
}
// 视频切换
const setVideoData = async (page: Pages) => {
    let { data: res } = await Api.getPlaymp4UrlData(page.cid, videoData.value.data.View.aid)
    playerData.value = res.data.durl
}
// 收藏
const collectionVideo = (d: DefaultDetailData) => {
    let obj = {
        bvid: d.data.View.bvid,
        aid: d.data.View.aid,
        length: d.data.View.duration,
        title: d.data.View.title,
        play: d.data.View.stat.like,
        video_review: d.data.View.stat.view,
        pic: d.data.View.pic
    }
    if (localStorage.getItem('collection')) {
        let data = localStorage.getItem('collection') as string
        collection.value = JSON.parse(data)
        let count: number = 0
        collection.value.forEach(item => {
            if (item.aid !== obj.aid) {
                count++
            }
        })

        if (count === collection.value.length) {
            collection.value = [obj, ...collection.value]
        } else {
            collection.value = collection.value.filter(item => {
                return item.aid !== obj.aid
            })
        }
        // followUsers.value = arr
    } else {
        collection.value = [obj, ...collection.value]
    }

    localStorage.setItem('collection', JSON.stringify(collection.value))
}
// 点赞
const likeVideo = (d: DefaultDetailData) => {
    let obj = {
        bvid: d.data.View.bvid,
        aid: d.data.View.aid,
        length: d.data.View.duration,
        title: d.data.View.title,
        play: d.data.View.stat.like,
        video_review: d.data.View.stat.view,
        pic: d.data.View.pic
    }
    if (localStorage.getItem('like')) {
        let data = localStorage.getItem('like') as string
        like.value = JSON.parse(data)
        let count: number = 0
        like.value.forEach(item => {
            if (item.bvid !== obj.bvid) {
                count++
            }
        })
        console.log(count, like.value.length)
        if (count === like.value.length) {
            like.value = [obj, ...like.value]
        } else {
            like.value = like.value.filter(item => {
                return item.bvid !== obj.bvid
            })
        }
    } else {
        like.value = [obj, ...like.value]
    }

    localStorage.setItem('like', JSON.stringify(like.value))
}

const JudgeWhetherYouLikeIt = () => {
    if (localStorage.getItem('like')) {
        let arr = localStorage.getItem('like') as string
        let newArr: Array<any> = JSON.parse(arr)
        for (let i = 0; i < newArr.length; i++) {
            let item = newArr[i]
            if (item.bvid == props.bvid) {
                isLike.value = true
                break
            } else {
                isLike.value = false
            }
        }
    }

    if (localStorage.getItem('collection')) {
        let arr = localStorage.getItem('collection') as string
        let newArr: Array<any> = JSON.parse(arr)
        for (let i = 0; i < newArr.length; i++) {
            let item = newArr[i]
            if (item.bvid == props.bvid) {
                isCollection.value = true
                break
            } else {
                isCollection.value = false
            }
        }
    }
}
const videoshowel = ref<any>()


watch(videoData, () => {
    let time = setTimeout(() => {
        getDanMuData(videoData.value.data.View.cid)
        clearTimeout(time)
    }, 5000)
})

onMounted(() => {
    getVideoData()
    JudgeWhetherYouLikeIt()
    userBvid.value = props.bvid
    setTimeout(() => {

    }, 10000)

})

onBeforeUnmount(() => {
    // isGetVideoValue.value = false
})



</script>

<template>
    <div>
        <VideoShow ref="videoshowel" :pic="pic" :danmu="danmu" :time="time" :timelength="timelength"
            :reallyTimeLength="reallyTimeLength" :videoData="videoData" :playerData="playerData" :danmuData="danmuData">
        </VideoShow>
        <div>
            <VideoIntroduction :introductionData="introductionData" :videoData="videoData" class=" border-b" />

            <van-collapse v-model="activeNames" :border="false" v-if="!videoData?.data?.View.redirect_url">
                <van-collapse-item :title="videoData?.data?.View.title" name="1" size="large" :border="false">
                    {{ videoData?.data?.View.desc }}
                </van-collapse-item>
            </van-collapse>
        </div>
        <div>
            <div class=" flex justify-between items-center p-3 border-b" v-if="!videoData?.data?.View.redirect_url">
                <div class=" flex items-center " @click="$event => goToUser(videoData?.data?.View.owner.mid)">
                    <img :src="videoData?.data?.View.owner.face" alt="" class=" w-7 h-7 border rounded-full mr-2" />
                    <span>{{ videoData?.data?.View.owner.name }}</span>
                </div>
                <div>
                    <span class=" mr-3" @click="likeVideo(videoData), isLike = !isLike">
                        <van-icon name="good-job" size="20" :color="isLike ? '#fb7299' : ''" />
                    </span>
                    <span class="mr-3" @click="collectionVideo(videoData), isCollection = !isCollection">
                        <van-icon name="star" size="20" :color="isCollection ? '#fb7299' : ''" />
                    </span>
                    <span @click="">
                        <van-icon size="20" name="share" />
                    </span>
                </div>
            </div>
            <VideoEpisodes :epIdValue="epIdValue" :episodes="episodes" :sectionEpisodes="sectionEpisodes"
                :videoData="videoData" @getDanMuData="getDanMuData" @getVideoAndAnthology="getVideoAndAnthology" />
            <div class="flex overflow-auto p-3 border-b" v-if="videoData.data && videoData?.data?.View.pages.length > 1">
                <div v-for="p in videoData?.data?.View.pages" class=" shrink-0 border rounded-md mr-2"
                    :style="activeIndex === p.page ? colorData : ''" @click="activeIndex = p.page, setVideoData(p)">
                    <p class=" text-xs py-1 px-2 title whitespace-nowrap text-ellipsis overflow-hidden">{{ p.part }}</p>
                </div>
            </div>
        </div>
        <div class=" overflow-auto" v-if="videoData?.data?.View.ugc_season">
            <div class=" flex px-1 ">
                <div v-for="v in videoData?.data?.View.ugc_season.sections[0].episodes " :key="v.aid"
                    class=" w-32 flex-shrink-0 px-1" @click="goToVideos(v.bvid)">
                    <img :src="v.arc.pic" class="inline-block rounded-md">
                    <div>
                        <p class="line2" :class="{ 'line-active': userBvid === v.bvid }">{{ v.title }}</p>
                    </div>
                </div>
            </div>
        </div>
        <FRecommend :videoData="videoData" :sid="season_id" class=" border-b" />
        <RecommendComponent :videoData="videoData" class=" border-b" />
    </div>
</template>

<style>
.line2 {
    margin-top: 2.13333vmin;
    font-size: 3.2vmin;
    color: #505050;
    line-height: 4.26667vmin;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.line-active {
    color: #fb7299;
}
</style>
